#include "network.h"

#ifndef UGLY_HACK_FOR_THOSE_WHO_DONT_KNOW_HOWTO_INSTALL_SDL
#include <SDL/SDL.h>
#include <SDL/SDL_net.h>
#else
#include <SDL.h>
#include <SDL_net.h>
#endif


tcp_socket* tcp_socket_connect(const char *host, int port)
{
    IPaddress ip;
    TCPsocket tcpsock;

    if(SDLNet_ResolveHost(&ip, host, port) == -1)
    {
        return 0;
    }

    tcpsock = SDLNet_TCP_Open(&ip);
    if(!tcpsock)
    {
        return 0;
    }
    tcp_socket *s = mem_allocate(sizeof(TCPsocket));
    memcpy(s, &tcpsock, sizeof(TCPsocket));
    return s;
}

tcp_socket* tcp_socket_listen(int port)
{
    IPaddress ip;
    TCPsocket tcpsock;

    if(SDLNet_ResolveHost(&ip, NULL, port)==-1)
    {
        return 0;
    }

    tcpsock = SDLNet_TCP_Open(&ip);
    if(!tcpsock)
    {
        return 0;
    }
    tcp_socket *s = mem_allocate(sizeof(TCPsocket));
    memcpy(s, &tcpsock, sizeof(TCPsocket));
    return s;
}

tcp_socket* tcp_socket_accept(tcp_socket *s)
{
    // accept a connection coming in on server_tcpsock
    TCPsocket new_tcpsock;

    new_tcpsock = SDLNet_TCP_Accept(*(TCPsocket*)s);
    if(!new_tcpsock)
    {
        return 0;
    }
    tcp_socket *sock = mem_allocate(sizeof(TCPsocket));
    memcpy(sock, &new_tcpsock, sizeof(TCPsocket));
    return sock;
}

void tcp_socket_close(tcp_socket *s)
{
    SDLNet_TCP_Close(*(TCPsocket*)s);
}

int tcp_socket_send(tcp_socket *s, void *data, int len)
{
    return SDLNet_TCP_Send(*(TCPsocket*)s, data, len);
}

int tcp_socket_recv(tcp_socket *s, void *data, int len)
{
    return SDLNet_TCP_Recv(*(TCPsocket*)s, data, len);
}
